package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;

/**
 * Servlet implementation class DeleteStory
 */
public class DeleteStory extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DeleteStory() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Deletes a story fragment. If the deleted fragment is a part of a story, then the tree structure is updated to reflect
	 * the deletion. Notifications in the system are also revised for the same purpose. 
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int result;
		int f_storyId;
		boolean deleteSuccess;
		PreparedStatement stmt = null;
		Connection conn = new DBConnection().connect();
		PrintWriter out = response.getWriter();

		String f_requestType = request.getParameter("request_type");
		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
		}
		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				f_storyId = Integer.parseInt(request.getParameter("story_id"));
				int parentID = getParentID(conn, f_storyId);
				ArrayList<Integer> childrenID = findChildren(conn, f_storyId);
				stmt = conn.prepareStatement("DELETE FROM " + TableNames.STORIES_TABLE + " WHERE s_id = ?");
				stmt.setInt(1, f_storyId);
				result = stmt.executeUpdate();
				if (result == 1) {
					deleteSuccess = true;
					// Upon successful deletion, update the tree and organize the notifications
					updateTree(conn, childrenID, parentID);
					deleteNotificaitons(conn, f_storyId);
				} else {
					deleteSuccess = false;
				}

				if (f_requestType.equals("Web")) {
					request.setAttribute("deleteSuccess", deleteSuccess);
					// Redirect to profile page after the operation is completed
					request.getRequestDispatcher("GetProfile").forward(request,	response);
				} else if (f_requestType.equals("Android")) {
					JSONObject deleteResultJsonObject = new JSONObject();
					try {
						deleteResultJsonObject.put("deleteSuccess",	deleteSuccess);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.print(deleteResultJsonObject.toString());
				} else {
					// HANDLE?
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}
	/**
	 * Finds the IDs of the story fragments that are linked to the specified story fragment (children of this fragment)
	 * @param conn connection object to communicate with the database
	 * @param s_id ID of the story fragment that is being deleted from the system
	 * @return IDs of the story fragments which are linked to this fragment (children of this fragment)
	 */
	private ArrayList<Integer> findChildren(Connection conn,int s_id){
		ArrayList<Integer> childrenID = new ArrayList<Integer>();
		PreparedStatement stmt;
		ResultSet rs;
		try {
			stmt = conn.prepareStatement("SELECT s_id FROM " + TableNames.STORIES_TABLE + " WHERE parent = ?");
			stmt.setInt(1, s_id);
			rs = stmt.executeQuery();
			while(rs.next()){
				childrenID.add(rs.getInt("s_id"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return childrenID;
	}
	
	/**
	 * Finds the ID of the story fragment to which this fragment is linked to (parent of this fragment)
	 * @param conn connection object to communicate with the database
	 * @param s_id ID of the story fragment that is being deleted from the system
	 * @return ID of the story fragment to which this fragment is linked to (parent of this fragment). If the fragment
	 * is not linked to another fragment, then 0 is returned.
	 */
	private int getParentID(Connection conn,int s_id){
		PreparedStatement stmt;
		ResultSet rs;
		int parentID = -1;
		try {
			stmt = conn.prepareStatement("SELECT parent FROM " + TableNames.STORIES_TABLE + " WHERE s_id = ?");
			stmt.setInt(1, s_id);
			rs = stmt.executeQuery();
			if(rs.next()){
				parentID = rs.getInt("parent");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return parentID;
	}
	
	/**
	 * Deletes all notifications that are related to this story fragment from the system
	 * @param conn connection object to communicate with the database
	 * @param s_id ID of the story fragment that is being deleted from the system
	 */
	private void deleteNotificaitons(Connection conn, int s_id){
		
		PreparedStatement stmt;
		try {
			stmt = conn.prepareStatement("DELETE FROM " + TableNames.NOTIFICATION_TABLE + " WHERE target_s_id = ?");
			stmt.setInt(1, s_id);
			stmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Organizes the tree structure of the linked stories. Children story fragments of the deleted story
	 * are linked to the parent of the deleted story fragment. If the deleted fragment does not have a parent
	 * then the parent links of the children are set to NULL.
	 * @param conn connection object to communicate with the database
	 * @param childrenID IDs of children of the story fragment that is being deleted
	 * @param parentID ID of the parent of the story fragment that is being deleted
	 */
	private void updateTree(Connection conn, ArrayList<Integer> childrenID, int parentID){
		PreparedStatement stmt;
		for(int s_id : childrenID){
			try {
				stmt = conn.prepareStatement("UPDATE " + TableNames.STORIES_TABLE + " SET parent = ? WHERE s_id = ?");
				if(parentID <= 0){
					stmt.setNull(1, Types.INTEGER);
				}else{
					stmt.setInt(1, parentID);	
				}
				stmt.setInt(2, s_id);
				stmt.executeUpdate();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
